package com.webserver.http;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.format.SignStyle;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * HTTp请求对象
 * 该类的每一个实例表示一个HTTP请求内容
 * 每个请求由三个部分构成:
 * 请求行、消息头、消息正文。
 */
public class HttpServletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protocol;

    //
    private String requestURI;

    //
    private String queryString;

    //
    private Map<String ,String > parameters = new HashMap<>();


    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();
    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;

        //1.1解析请求行。
        parseRequestLine();

        //1.2解析消息头。
        parseHeaders();

        //1.3解析消息正文。
        parseContent();
    }

    //解析请求行,parse: 解析。
    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line = readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println(line);
        //请求行相关信息
        method = line.substring(0,line.indexOf(" "));//请求方式
        uri = line.substring(line.indexOf(" ")+1,line.lastIndexOf(" "));//抽象路径
        protocol = line.substring(line.lastIndexOf(' ')+1);//协议版本
        parseURI();
//            String[] array = line.split("\\s");
//            method = array[0];   //获取split拆分空格前的字符串。
//            uri = array[1];      //获取split拆分字符串的第二段。
//            protocol = array[2]; //获取split拆分字符串的第三段。
        System.out.println("method: "+method);
        System.out.println("uri: "+uri);
        System.out.println("requestURI: "+requestURI);
        System.out.println("queryString: "+queryString);
        System.out.println("parameters: "+parameters);
        System.out.println("protocol: "+protocol);
    }

    private void parseURI(){
//        String[] data = uri.split("\\?");
//        requestURI = data[0];
//        if (data.length>1){//若大于1说明问号后面有参数部分
//            queryString = data[1];
//            data = queryString.split("&");
//            for (String para : data){
//                String[] paras = para.split("=");
//                parameters.put(paras[0],paras.length>1?paras[1]:null);
//            }
//
//        }
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length>1){
            queryString = data[1];
            parseParameter(queryString);
        }


//        if (uri.contains("?")) {
//            requestURI = uri.substring(0, uri.indexOf("?"));
//            queryString = uri.substring(uri.indexOf("?")+1);
//            if (queryString.contains("&")){
//                String[] array = queryString.split("&");
//                for (int i=0; i<array.length; i++){
//                    String key = array[i].substring(0,array[i].indexOf("="));
//                    String value = array[i].substring(array[i].indexOf("="));
//                    parameters.put(key,value);
//                    }
//                }
//        }else {
//            requestURI = uri;
//        }
    }

    //解析消息头
    private void parseHeaders() throws IOException {
        String line;
        //循环读取消息头信息，读取到为空串时，停止循环，消息头读取完毕！
        while (!(line = readLine()).isEmpty()){
            System.out.println("消息头: "+line);
            /**
                String array = line.split("\\s");
                headers.put(array[0],array[1]);
             */
            String key = line.substring(0,line.indexOf(": "));
            String value = line.substring(line.indexOf(": ")+2);
            headers.put(key,value);
        }
        headers.forEach((k,v)-> System.out.println(k+v));
    }

    //解析消息正文
    private void parseContent() throws IOException {
        if ("post".equalsIgnoreCase(method)){
            System.out.println("++++++++++"+method);
            if (headers.containsKey("Content-Length")){
                int contentLength = Integer.parseInt(headers.get("Content-Length"));
                System.out.println("+++++++++++++++++++++++++++++++++++++"+contentLength);

                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(data);

                if (headers.containsKey("Content-Type")){
                    String contentType = headers.get("Content-Type");

                    System.out.println("+++++++++++++++++++++++++++="+contentType);
                    if ("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容: "+line);
                        parseParameter(line);
                    }
                }





            }
        }
    }
    public void parseParameter(String  line){
            String[] data  = line.split("&");
            for (String para : data){
                String[] paras = para.split("=");
                parameters.put(paras[0],paras.length>1?paras[1]:null);
            }
        }


    /*
        通过socket获取的输入流读取客户端发送过来的一行字符串。
     */
    private String readLine() throws IOException {
        //获取客户端发过来的消息。
        InputStream in = socket.getInputStream();
        char pre = 'a',cur;
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d = in.read())!=-1){
            cur = (char)d;
            if (pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name){
        return parameters.get(name);
    }
}
